package com.frank.oj.service.admin.account.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frank.model.entity.user.Session;
import com.frank.model.entity.user.UserInfo;
import com.frank.oj.common.exception.StatusAccessDeniedException;
import com.frank.oj.common.exception.StatusFailException;
import com.frank.oj.common.result.CommonResult;
import com.frank.oj.common.result.ResultStatus;
import com.frank.oj.constant.ShiroConstant;
import com.frank.oj.manager.AdminAccountManager;
import com.frank.oj.model.dto.LoginDTO;
import com.frank.oj.model.vo.UserInfoVO;
import com.frank.oj.service.admin.account.AdminAccountService;
import com.frank.oj.service.entity.user.SessionEntryService;
import com.frank.oj.service.entity.user.UserInfoEntityService;
import com.frank.oj.utils.RedisUtils;
import com.jthinking.common.util.ip.IPInfo;
import com.jthinking.common.util.ip.IPInfoUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author frank
 * @Date 2024/3/27
 */
@Service
public class AdminAccountServiceImpl implements AdminAccountService {

    @Resource
    private AdminAccountManager adminAccountManager;
    @Resource
    private SessionEntryService sessionEntryService;
    @Resource
    private UserInfoEntityService userInfoEntityService;
    @Resource
    private RedisUtils redisUtils;
    @Override
    public CommonResult<UserInfoVO> login(LoginDTO loginDto) {
        try {
            return CommonResult.successResponse(adminAccountManager.login(loginDto));
        } catch (StatusFailException e) {
            return CommonResult.errorResponse(e.getMessage());
        } catch (StatusAccessDeniedException e) {
            return CommonResult.errorResponse(e.getMessage(), ResultStatus.ACCESS_DENIED);
        }
    }

    @Override
    public CommonResult<Void> logout() {
        adminAccountManager.logout();
        return CommonResult.successResponse("已退出登录");

    }

    @Override
    @Deprecated
    public IPage<HashMap<String, Object>> getUserSystemLogs(Integer currentPage, Integer limit, String userName, String nickName) {
        if (currentPage == null || currentPage<0){
            currentPage = 1;
        }
        if (limit == null || limit<0){
            limit = 10;
        }
        Page<HashMap<String, Object>> page = new Page<>(currentPage, limit);

        List<HashMap<String, Object>> result = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();

        if (StringUtils.isEmpty(userName)) {
            List<Session> sessionList = sessionEntryService.list();
            for (Session session : sessionList) {
                LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UserInfo::getUuid, session.getUid());
                UserInfo userInfo = userInfoEntityService.getOne(wrapper);
                if (userInfo != null) {
                    map.put("userName", userInfo.getUsername());
                    map.put("nickName", userInfo.getNickname());
                    map.put("IP", session.getIp());
                    IPInfo ipInfo = IPInfoUtils.getIpInfo(session.getIp());
                    String address = ipInfo.getCountry() + ":" + ipInfo.getProvince() + ipInfo.getAddress() + "|" + ipInfo.getIsp();
                    map.put("address", address);

                    map.put("gmtCreate", session.getGmtCreate());
                    result.add(map);
                }
            }
        } else {
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(UserInfo::getUsername, userName).orderByDesc(UserInfo::getGmtCreate);

            List<UserInfo> list = userInfoEntityService.list(queryWrapper);

            for (UserInfo userInfo : list) {

                LambdaQueryWrapper<Session> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Session::getUid, userInfo.getUuid()).orderByDesc(Session::getGmtCreate);
                List<Session> sessionList = sessionEntryService.list(wrapper);

                for (Session session : sessionList) {
                    map.put("userName", userInfo.getUsername());
                    map.put("nickName", userInfo.getNickname());
                    map.put("IP", session.getIp());
                    IPInfo ipInfo = IPInfoUtils.getIpInfo(session.getIp());
                    String address = ipInfo.getCountry() + ":" + ipInfo.getProvince() + ipInfo.getAddress() + "|" + ipInfo.getIsp();
                    map.put("address", address);
                    map.put("gmtCreate", session.getGmtCreate());
                    result.add(map);
                }
            }
        }
        page.setRecords(result);
        return page;
    }

    @Override
    public void forcedOffline(String userName) {

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(UserInfo::getUuid).eq(UserInfo::getUsername,userName);

        UserInfo userInfo = userInfoEntityService.getOne(queryWrapper);

        redisUtils.del(ShiroConstant.SHIRO_TOKEN_KEY + userInfo.getUuid());
    }
}
